package storeMovie.Util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import storeMovie.JavaBean.Movie;

public class MovieManager {
	//private Session session = null;

	public MovieManager() {
		//session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		//session.beginTransaction();
	}
	
	public Movie getMovie(int movieId) {
		Session session=null;
		Movie movie = null;
		try{
			session = HibernateUtil.currentSession();
			movie = (Movie)session.get(Movie.class, new Integer(movieId));
		}catch (Exception e) {
			System.out.println(e.getCause());// TODO: handle exception
			//return movie;
		}
		return movie;
	}
	
	public void updateMovie(Movie movie) {
		Session session=null;
		Transaction t = null;
		try{
			session = HibernateUtil.currentSession();
			t=session.beginTransaction();
			session.update(movie);
			t.commit();
		}catch (Exception e) {
			e.printStackTrace();
			t.rollback();
		}
	}
	
	public List<Movie> getMovie(){
		Session session=null;
		List<Movie> listMovies = null;
		try{
			session = HibernateUtil.currentSession();
			Query query = session.createQuery("from Movie m ORDER BY m.movieTotalSell DESC");
			query.setMaxResults(6);
			listMovies = query.list();
			return listMovies;
		}catch (Exception e) {
			System.out.println(e.getCause());// TODO: handle exception
		}
		return listMovies;
	}
	public List<Movie> getMovieByName(String movieName){
		List<Movie> listMovie =null;
		Session session=null;
		try{
			session = HibernateUtil.currentSession();
			Query query = session.createQuery("from Movie m where m.movieName like ?");
			query.setParameter(0, movieName);
			listMovie = query.list();
			return listMovie;
		}catch (Exception e) {
			System.out.println(e.getCause());// TODO: handle exception
		}
		return listMovie;
	}
	
	public List<Movie> getMovieByCategory(int categoryId){
		List<Movie> listMovie =null;
		Session session=null;
		try{
			session = HibernateUtil.currentSession();
			Query query = session.createQuery("from Movie m where m.movieCategory = ? Order by m.movieTotalSell DESC");
			query.setParameter(0, categoryId);
			query.setMaxResults(6);
			listMovie = query.list();
			return listMovie;
		}catch (Exception e) {
			System.out.println(e.getCause());// TODO: handle exception
		}
		return listMovie;
	}

}
